<script setup>
import {DownloadOutlined, InfoCircleOutlined} from '@ant-design/icons-vue'
import {message} from 'ant-design-vue'
import JSZip from "jszip";
import saveAs from 'jszip/vendor/FileSaver.js'
import {getCurrentInstance, watch} from 'vue'
import {utils, writeFile} from 'xlsx'
import {isLogin} from '~/logic'
import {TRequest} from "~/utils/ali/PCRequest";
import {cache} from "~/utils/Cache";
import {delete_rows} from '~/utils/deleteRows'

const emit = defineEmits(['login'])
const instance = getCurrentInstance()
const item = getCurrentInstance().proxy.$item
const __option = getCurrentInstance()?.appContext.provides.option;
const handle = async () => {
  if (isLogin({emit}, __option)) {
    visible.value = true
    startLoad();
  }
}
const startLoad = () => {

  page.value = 1
  loading.value = true
  loaded.value = false
  dataSource.value = []
  loadData()
}
const visible = ref(false)
const dataSource = ref([])
const loaded = ref(false)
const loading = ref(false)
const page = ref(1)
let timer = null;
const loadData = () => {
  if (!loading.value) return
  if (loaded.value) return
  TRequest.itemShowList(item.itemId(), page.value).then(res => {
    res.model.buyerShow.feeds.forEach(item => {
      item.images = item.content.elements.map(img => {
        return img.mainPicUrl;
      });
    });
    if (page.value === 1) {
      dataSource.value = res.model.buyerShow.feeds;
    } else {
      dataSource.value = dataSource.value.concat(res.model.buyerShow.feeds);
    }
    page.value++
    if (res.model.qince.pagination.hasMore === "false") {
      loaded.value = true
      loading.value = false;
    } else {
      timer = setTimeout(() => {
        loadData()
      }, 3000)
    }
  })
}
const downloading = ref(false)
const downloadZip = async () => {
  downloading.value = true;
  message.info('正在下载，请耐心等待~');
  if (dataSource.value.length === 0) {
    downloading.value = false;
    message.error('无买家秀数据~')
    return
  }
  const zip = new JSZip();
  for (let i = 0; i < dataSource.value.length; i++) {
    const item = dataSource.value[i];
    const folder = zip.folder(item.account.accountNick);
    const dir = folder.folder(item.uuid);
    for (const img of item.images) {
      const i = item.images.indexOf(img);
      const response = await fetch(img)
      const blob = await response.blob()
      dir.file(`图片-${i + 1}.jpg`, blob);
    }
    dir.file('内容.txt', item.content.richText);
  }
  zip.generateAsync({type: "blob"}).then(function (content) {
    saveAs(content, `[星察数据]买家秀_${item.itemId()}.zip`);
  });
  downloading.value = false;
  message.success('下载成功~');
}
const columns = [
  {
    dataIndex: 'account.accountNick',
    title: '昵称',
    dataType: 'custom',
    slot: 'account',
    width: 200,
  },
  {
    dataIndex: 'images',
    title: '图片',
    dataType: 'custom',
    slot: 'images',
    align: 'center',
  },
  {
    dataIndex: 'content.richText',
    title: '内容',
  },
  {
    dataIndex: 'interact.favourCount',
    title: '点赞数',
    width: 100,
    sorter: (a, b) => parseInt(a.interact.favourCount) - parseInt(b.interact.favourCount),
  },
];
// 离开界面时清除定时器
onUnmounted(() => {
  if (timer) clearTimeout(timer)
})
</script>

<template>
  <div class="inner-box bold btn" @click="handle">
    买家秀下载
    <!--    <CaretDownOutlined /> -->
  </div>
  <a-modal v-model:visible="visible" :title="`买家秀下载-${item.itemId()}`" :footer="false" width="90%" style="top: 20px;">
    <a-spin size="large" :spinning="dataSource.length===0 && loaded===false">
      <a-empty v-if="dataSource.length===0 && loaded" title="无买家秀数据~" description="无买家秀数据~"
               style="padding: 200px 0;"
      />
      <base-table :table-name="`买家秀_${item.itemId()}`" :data-source="dataSource" :columns="columns" v-else-if="dataSource.length>0" style="height: 530px;">
        <template #toolbar>
          <a-row type="flex">
            <a-col>
              <a-button type="primary" size="small" @click="downloadZip" :loading="downloading">买家秀下载</a-button>
            </a-col>
            <a-col style="padding-left: 5px;">
              <div style="color: #666666;font-size: 12px;display: inline-block;line-height: 2;padding-right: 10px;">
                已加载 {{ dataSource.length }} 条买家秀
              </div>
              <a-button v-if="loading" size="small" type="primary" @click="loading=false">暂停加载</a-button>
              <a-button v-else-if="!loaded && !loading" size="small" type="primary"
                        @click="()=>{loading=true;loadData();}"
              >继续加载
              </a-button>
              <a-button v-else size="small" @click="startLoad()">重新加载</a-button>
            </a-col>
            <a-col flex="1">
              <div style="text-align: center;">
                <div
                    style="background: #eee;display: inline-block;border-radius: 10px;padding:5px 10px;font-size: 12px;color: #666;"
                >
                  <InfoCircleOutlined style="padding-right: 5px;"/>
                  星察数据下载文件和数据仅供学习和参考，切勿私自商用造成侵权！
                </div>
              </div>
            </a-col>
          </a-row>
        </template>
        <template #account="record">
          <a-row type="flex">
            <a-col>
              <a-image :src="record.account.avatarUrl"
                       style="width: 30px;height: 30px;border-radius: 5px;overflow: hidden;"
              />
            </a-col>
            <a-col flex="1" style="display: flex;align-items: center;padding-left: 5px;">
              {{ record.account.accountNick }}
            </a-col>
          </a-row>
        </template>
        <template #images="record">
          <a-row :gutter="5">
            <a-col v-for="img in record.images" :span="6" :key="img" style="margin-right: 5px;">
              <a-image :src="img" style="width: 100%;"/>
            </a-col>
          </a-row>
        </template>
      </base-table>
      <div v-else style="height: 530px;">

      </div>
    </a-spin>
  </a-modal>
</template>

<style scoped>
</style>
